package com.example.demo;

import com.nowcoder.community.qidong;
import com.nowcoder.community.x_config.RedisConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = qidong.class)
public class RedisT {
    @Autowired
    private RedisTemplate redisTemplate;//返回null异常。就是上面没写3个@

    @Test
    public void T(){
        String k = "test:name";
        System.out.println(redisTemplate);
        redisTemplate.opsForValue().set(k,1);
        redisTemplate.opsForValue().set(k,2);
        redisTemplate.opsForValue().set(k,3);
        System.out.println(redisTemplate.opsForValue().get(k));

    }

    @Test
    public void T2(){
        String k = "mh:sanguo";
        redisTemplate.opsForSet().add(k,"用户1","用户2","用户3");
        System.out.println(redisTemplate.opsForSet().members(k));

    }

    //编程式事务
    @Test
    public void T3(){
        Object o = redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.multi();

                String k = "mh:sanguo";
                redisTemplate.opsForSet().add(k,"1");
                redisTemplate.opsForSet().add(k,"2");
                redisTemplate.opsForSet().add(k,"3");
                //System.out.println(redisOperations.opsForSet().members(k));//k就是set！[查询不能写在redis事务里]
                return redisOperations.exec();
            }
        });

        System.out.println(o);
    }
}
